/*
 * author      : 吴中勤 
 * date        : 2019/3/13
 * description : TODO
 */

package org.wzq.learn.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wzq.learn.AppRuntimeEnv;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Service
public class ThreadPoolService {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolService.class);

    private static final int corePoolSize = 1;
    private static final int maxPoolSize = 1;
    private static final int queueSize = 100;
    private static final int keepAliveTime = 10; // second

    @Autowired
    private AppRuntimeEnv appRuntimeEnv;
    private ThreadLocalThreadPoolExecutor executorPool;

    @PostConstruct
    public void initThreadPoolExecutor() {
        ThreadFactory threadFactory = (Runnable r) -> new AppRuntimeEnvThread(r);

        executorPool = new ThreadLocalThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize),
                threadFactory
        );
    }


    public void executor(Runnable r) {
        if (logger.isInfoEnabled()) logger.info("executorPool queue size=" + executorPool.getQueue().size());
        executorPool.execute(new RunnableWrapper(r, appRuntimeEnv));
    }

    public <T> Future<T> submit(Callable<T> t) {
        return executorPool.submit(new CallableWrapper<T>(t, appRuntimeEnv));
    }

}
